package com.ytjj.qmyx.supplychain.common.utils;

import com.alibaba.fastjson.JSON;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import lombok.val;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class BeanUtils {

	public static <T1, T2> List<T2> convert(List<T1> sourceList, Class<T2> toType) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyList();
		}
		return sourceList.parallelStream().map(item -> convert(item, toType)).collect(Collectors.toList());
	}

	public static <T1, T2> T2 convert(T1 source, Class<T2> toType) {
		if (null == source) {
			return null;
		}
		T2 target = null;
		try {
			target = toType.newInstance();
		} catch (Exception e) {
			throw new ApiException("数据转换异常", e);
		}
		org.springframework.beans.BeanUtils.copyProperties(source, target);
		return target;
	}


	public static <T> String beanToString(T value) {
		if (value == null) {
			return null;
		}
		Class<?> clazz = value.getClass();
		if (clazz == int.class || clazz == Integer.class) {
			return "" + value;
		} else if (clazz == String.class) {
			return (String) value;
		} else if (clazz == long.class || clazz == Long.class) {
			return "" + value;
		} else {
			return JSON.toJSONString(value);
		}
	}


}
